#import "EGORefreshTableHeaderView.h"

#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

#define  RefreshHeaderHight 45.0f

@interface EGORefreshTableHeaderView (Private)
- (void)setState:(EGOHeaderPullRefreshState)aState;
@end

@implementation EGORefreshTableHeaderView

@synthesize delegate=_delegate;

- (id)initWithFrame:(CGRect)frame {
    if((self = [super initWithFrame:frame])) {
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		self.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];

		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 52.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont systemFontOfSize:12.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		_lastUpdatedLabel=label;
        _lastUpdatedLabel.hidden = YES;
		[label release];
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 35.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont boldSystemFontOfSize:13.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		_statusLabel=label;
        _statusLabel.transform = CGAffineTransformMakeRotation(90 * M_PI / 180.0);
		[label release];
		
		[self setState:EGOHEADERPullRefreshNormal];
    }
    return self;
}

#pragma mark -
#pragma mark Setters

- (void)refreshLastUpdatedDate {
	if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)]) {
		NSDate *date = [_delegate egoRefreshTableHeaderDataSourceLastUpdated:self];
		[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateStyle:NSDateFormatterShortStyle];
		[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        _lastUpdatedLabel.text = [NSString stringWithFormat:@"上次更新: %@", [dateFormatter stringFromDate:date]];
		[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
		[[NSUserDefaults standardUserDefaults] synchronize];
	} else {
		_lastUpdatedLabel.text = nil;
	}
}

- (void)setState:(EGOHeaderPullRefreshState)aState{
	switch (aState) {
		case EGOHEADERPullRefreshPulling:
            _statusLabel.text = NSLocalizedString(@"制冷", @"Release");
			break;
		case EGOHEADERPullRefreshNormal:
            _statusLabel.text = NSLocalizedString(@"最新", @"Keep Going");
//            [_indicator stopAnimating];
			[self refreshLastUpdatedDate];
			break;
		case EGOHEADERPullRefreshLoading:
            _statusLabel.text = NSLocalizedString(@"制冷中", @"It is a ...");
			break;
		default:
			break;
	}
	_state = aState;
}

#pragma mark -
#pragma mark ScrollView Methods

- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {
//    Log(@"MARK %f %f",scrollView.contentOffset.x, scrollView.contentOffset.y);
//    int tmpA = (abs(scrollView.contentOffset.y)>=60?59:abs(scrollView.contentOffset.y))/6 + 1;
//    if( tmpA != alpha){
//        alpha = tmpA;
//        Log(@"MARK %d %f",tmpA, scrollView.contentOffset.y);
//        _indicator.alpha = 0.1f * alpha;
//    }
	if (_state == EGOHEADERPullRefreshLoading) {
		CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
		offset = MIN(offset, 60);
		scrollView.contentInset = UIEdgeInsetsMake(offset, 0.0f, 0.0f, 0.0f);
	} else if (scrollView.isDragging) {
		BOOL _loading = NO;
		if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
			_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
		}
        if ( scrollView.contentOffset.y < 0 ) {
            //            Log(@"MARK %d %f",tmpR, scrollView.contentOffset.y);
            int tmpR = 8 - ((int)(abs(scrollView.contentOffset.y)/4)%8);
            if( tmpR != rolling){
                rolling = tmpR;
                [_delegate egoRefreshTableHeaderDidStart:self :rolling];
            }
		}else if(scrollView.contentOffset.y + scrollView.frame.size.height < scrollView.contentSize.height - 40){
            [_delegate egoRefreshTableHeaderDidStop:self];
        }
		if (_state == EGOHEADERPullRefreshPulling && scrollView.contentOffset.y > -RefreshHeaderHight && scrollView.contentOffset.y < 0.0f && !_loading) {
			[self setState:EGOHEADERPullRefreshNormal];
		} else if (_state == EGOHEADERPullRefreshNormal && scrollView.contentOffset.y < -RefreshHeaderHight && !_loading) {
			[self setState:EGOHEADERPullRefreshPulling];
		}
		if (scrollView.contentInset.top != 0) {
			scrollView.contentInset = UIEdgeInsetsZero;
		}
	} else {
        [_delegate egoRefreshTableHeaderDidStop:self];
    }
}

- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
	BOOL _loading = NO;
	if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
		_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
	}
	if (scrollView.contentOffset.y <= -RefreshHeaderHight && !_loading) {
		if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
			[_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
		}
		[self setState:EGOHEADERPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
	}
}

- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	[self setState:EGOHEADERPullRefreshNormal];
}

#pragma mark -
#pragma mark Dealloc

- (void)dealloc {
	_delegate=nil;
	_statusLabel = nil;
	_lastUpdatedLabel = nil;
    [super dealloc];
}

@end
